<template>
  <el-card style="width: 500px; margin-top: 50px; padding-top: 10px">
    <el-form
      :model="form"
      :rules="rules"
      ref="userForm"
      label-width="150px"
      size="small"
    >
      <el-form-item prop="password" label="请输入原密码：">
        <el-input v-model="form.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item prop="newPassword" label="请输入新密码：">
        <el-input v-model="form.newPassword" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword" label="请再次输入新密码：">
        <el-input v-model="form.confirmPassword" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">确 定</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: 'FrontPassword',
  data() {
    return {
      form: {
        password: '',
        newPassword: '',
        confirmPassword: ''
      },
      user: JSON.parse(localStorage.getItem('curUser')) || {},
      rules: {
        password: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    save() {
      this.$refs['userForm'].validate(valid => {
        if (valid) {
          // 表单校验合法
          if (this.form.password === this.user.password) {
            if (this.form.newPassword === this.form.confirmPassword) {
              this.$http
                .post(
                  '/user/password/' + this.user.id + '/' + this.form.newPassword
                )
                .then(res => {
                  if (res.code === '200') {
                    this.$message.success('密码修改成功!请重新登录')
                    localStorage.removeItem('user')
                    this.$router.push('/login')
                  } else {
                    this.$message.error('密码修改失败!')
                  }
                })
            } else {
              this.$message.error('两次输入的密码不一致，请重新输入')
            }
          } else {
            this.$message.error('原密码错误，请重新输入')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped></style>
